<template>
  <div class="fx-radio-button" @click="radioButtonClick"
       :class="[radioGroupSize!==''?radioGroupSize:size,{active:label===radioButtonValue,disabled:(radioGroupDisabled||disabled)}]">
    <input type="radio" hidden :name="radioButtonValue" :value="label">
    <slot></slot>
  </div>
</template>

<script lang="ts">
import { defineComponent, inject, PropType } from 'vue'
import { Emitter } from 'mitt'
import { ComponentSize, componentSizeArr } from '@/base/types'

interface RadioButton {
  label: string | number,
  size: ComponentSize,
  disabled: boolean
}

export default defineComponent({
  name: 'FRadioButton',
  props: {
    // 选项
    label: {
      type: [String, Number] as PropType<string | number>,
      default: '',
      required: true
    },
    // 大小
    size: {
      type: String as PropType<ComponentSize>,
      default: 'default',
      validator (val: ComponentSize): boolean {
        return componentSizeArr.includes(val)
      }
    },
    // 禁用
    disabled: {
      type: Boolean as PropType<boolean>,
      default: false
    }
  },
  setup (props: RadioButton) {
    // 获取来自radioGroup emit
    const radioGroupEmit = inject<Emitter['emit'] | undefined>('radioGroupMittEmit', undefined)
    // 获取来自radioGroup 选中
    const radioButtonValue = inject('radioGroupValue', { value: '' })
    // 取货来自radioGroup 禁用
    const radioGroupDisabled = inject('radioGroupDisabled', true)
    // 取货来自radioGroup 禁用
    const radioGroupSize = inject('radioGroupSize', '')

    // 单选按钮点击
    const radioButtonClick = (): void => {
      if (props.disabled || radioGroupDisabled) return
      // 当存在radioGroup父级时生效
      if (radioGroupEmit) radioGroupEmit('radioGroupClick', props.label)
    }

    return {
      radioGroupSize,
      radioButtonValue,
      radioGroupDisabled,
      radioButtonClick
    }
  }
})
</script>
